package com.dream.wuliu.utils;

import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.util.concurrent.TimeUnit;

import org.androidannotations.annotations.App;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.EBean.Scope;

import retrofit.RequestInterceptor;
import retrofit.RestAdapter;
import retrofit.client.OkClient;

import com.dream.wuliu.base.MyApplication;
import com.dream.wuliu.base.MyErrorHandler;
import com.dream.wuliu.view.R;
import com.squareup.okhttp.OkHttpClient;

/**
 * 
 * @author EvanYu
 *
 */
@EBean(scope = Scope.Singleton)
public class ServiceBuilder {
	
	 @App
	 MyApplication app;
	  
	private static RequestInterceptor interceptor ;
	static{
		
		final CookieManager cookieManager = new CookieManager();
		cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
		CookieHandler.setDefault(cookieManager);
		 interceptor = new RequestInterceptor() {
		  @Override
		  public void intercept(RequestFacade request) {
		    for (HttpCookie cookie : cookieManager.getCookieStore().getCookies()) {
		       request.addHeader("Cookie", cookie.getValue());
		    }
		  }
		};
		
	}
	 
	public  <E> E buildService(Class<E> cls){
		
		
		OkHttpClient client = new OkHttpClient();
		client.setReadTimeout(10000L, TimeUnit.MILLISECONDS);
		client.setConnectTimeout(1500L, TimeUnit.MILLISECONDS);
		RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(app.getStr(R.string.server_name))
				.setClient(new OkClient(client)) .setErrorHandler(new MyErrorHandler()).setRequestInterceptor(interceptor) .build();
		E service = restAdapter.create(cls);
		return service;
		
	}
}
